import { api } from './api'
import type { ApiResponse } from '../types'

interface DashboardStats {
  totalUsers: number
  totalArticles: number
  totalComments: number
  totalViews: number
  totalLikes: number
  newUsersToday: number
  newArticlesToday: number
  newCommentsToday: number
  activeUsers: {
    id: number
    username: string
    avatar?: string
    articleCount: number
    commentCount: number
  }[]
  popularArticles: {
    id: number
    title: string
    viewCount: number
    likeCount: number
    commentCount: number
    author: {
      id: number
      username: string
      avatar?: string
    }
  }[]
}

interface TimeRange {
  startDate: string
  endDate: string
}

interface ArticleStats {
  totalArticles: number
  totalViews: number
  totalLikes: number
  totalComments: number
  articlesByCategory: {
    categoryId: number
    categoryName: string
    count: number
  }[]
  articlesByTag: {
    tagId: number
    tagName: string
    count: number
  }[]
  viewsTrend: {
    date: string
    count: number
  }[]
  likesTrend: {
    date: string
    count: number
  }[]
  commentsTrend: {
    date: string
    count: number
  }[]
}

interface UserStats {
  totalUsers: number
  activeUsers: number
  newUsers: number
  usersByRole: {
    role: string
    count: number
  }[]
  registrationTrend: {
    date: string
    count: number
  }[]
  activityTrend: {
    date: string
    articles: number
    comments: number
    likes: number
  }[]
}

export const statsApi = api.injectEndpoints({
  endpoints: (builder) => ({
    getDashboardStats: builder.query<ApiResponse<DashboardStats>, void>({
      query: () => '/stats/dashboard',
      providesTags: ['Stats'],
    }),

    getArticleStats: builder.query<ApiResponse<ArticleStats>, TimeRange>({
      query: (params) => ({
        url: '/stats/articles',
        params,
      }),
      providesTags: ['Stats'],
    }),

    getUserStats: builder.query<ApiResponse<UserStats>, TimeRange>({
      query: (params) => ({
        url: '/stats/users',
        params,
      }),
      providesTags: ['Stats'],
    }),

    getArticleViewStats: builder.query<ApiResponse<{ date: string; count: number }[]>, number>({
      query: (articleId) => `/stats/articles/${articleId}/views`,
      providesTags: (_, __, id) => [{ type: 'Stats', id }],
    }),

    getUserActivityStats: builder.query<
      ApiResponse<{
        articles: number
        comments: number
        likes: number
        views: number
      }>,
      number
    >({
      query: (userId) => `/stats/users/${userId}/activity`,
      providesTags: (_, __, id) => [{ type: 'Stats', id }],
    }),
  }),
})

export const {
  useGetDashboardStatsQuery,
  useGetArticleStatsQuery,
  useGetUserStatsQuery,
  useGetArticleViewStatsQuery,
  useGetUserActivityStatsQuery,
} = statsApi 